package com.ruoyi.goods.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.distributor.domain.DistributionUser;
import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.service.IMerchantService;
import com.ruoyi.newsInfo.domain.NewsInfo;
import com.ruoyi.distributor.service.IDistributionUserService;
import com.ruoyi.distributionRelation.service.IDistributionRelationCacheService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.goods.domain.Goods;
import com.ruoyi.goods.service.IGoodsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品信息Controller
 *
 * @author ruoyi
 * @date 2025-06-01
 */
@RestController
@RequestMapping("/ruoyi/goods")
public class GoodsController extends BaseController
{
    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IMerchantService merchantService;

    @Autowired
    private IDistributionUserService distributionUserService;

    @Autowired
    private IDistributionRelationCacheService distributionRelationCacheService;

    @Value("${miniapp.merchant-id:8}")
    private Long miniAppMerchantId;

    /**
     * 根据标记信息来查询商品列表（管理端）
     * @param tags 标记信息（1="热销",2="促销",3="新品"）
     * @return 分页数据
     */
    @GetMapping("/listByTags")
    public TableDataInfo listByTags(String tags) {

        // 构造查询条件
        Goods goods = new Goods();
        goods.setTags(tags);

        // 判断是否为管理员
        Long userId = getUserId();
        if (!getLoginUser().getUser().isAdmin()) {
            // 非管理员用户需要设置商家ID
            Merchant merchantInfo = merchantService.selectMerchantByUserId(userId);
            Long merchantId = merchantInfo != null ? merchantInfo.getMerchantId() : null;

            // 非商家用户返回空数据
            if (merchantId == null) {
                return getDataTable(new ArrayList<>());
            }

            goods.setMerchantId(merchantId);
        }

        // 执行查询
        startPage();
        List<Goods> list = goodsService.selectGoodsListByTags(goods);
        return getDataTable(list);
    }

    /**
     * 小程序端根据标记信息来查询商品列表（公开接口）
     * @param tags 标记信息（1="热销",2="促销",3="新品"）
     * @return 商品列表
     */
    @GetMapping("/miniapp/listByTags")
    public AjaxResult miniappListByTags(String tags) {
        // 小程序端使用固定的商家ID
        Long merchantId = getMiniAppMerchantId();

        if (merchantId == null) {
            return AjaxResult.error("未配置小程序商家ID");
        }

        // 构造查询条件
        Goods goods = new Goods();
        goods.setMerchantId(merchantId);
        goods.setTags(tags);

        // 执行查询
        List<Goods> list = goodsService.selectGoodsListByTags(goods);
        return AjaxResult.success(list);
    }

    /**
     * 查询商品信息列表（管理端）
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:goods:list')")
    @GetMapping("/list")
    public TableDataInfo list(Goods goods)
    {
        startPage();
        List<Goods> list = goodsService.selectGoodsList(goods);
        return getDataTable(list);
    }

    /**
     * 小程序端查询商品信息列表（公开接口）
     */
    @GetMapping("/miniapp/list")
    public AjaxResult miniappList() {
        // 小程序端使用固定的商家ID
        Long merchantId = getMiniAppMerchantId();

        if (merchantId == null) {
            return AjaxResult.error("未配置小程序商家ID");
        }

        // 构造查询条件
        Goods goods = new Goods();
        goods.setMerchantId(merchantId);

        // 执行查询
        List<Goods> list = goodsService.selectGoodsList(goods);
        return AjaxResult.success(list);
    }

    /**
     * 导出商品信息列表
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:goods:export')")
    @Log(title = "商品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Goods goods)
    {
        List<Goods> list = goodsService.selectGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        util.exportExcel(response, list, "商品信息数据");
    }

    /**
     * 获取商品信息详细信息（管理端）
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:goods:query')")
    @GetMapping(value = "/{goodsId}")
    public AjaxResult getInfo(@PathVariable("goodsId") Long goodsId)
    {
        return success(goodsService.selectGoodsByGoodsId(goodsId));
    }

    /**
     * 小程序端获取商品信息详细信息（公开接口）
     * 支持分销关系自动绑定功能
     */
    @GetMapping("/miniapp/{goodsId}")
    public AjaxResult miniappGetInfo(@PathVariable("goodsId") Long goodsId,
                                    @RequestParam(value = "distributorCode", required = false) String distributorCode,
                                    @RequestParam(value = "inviteCode", required = false) String inviteCode)
    {
        // 检查商品ID是否有效
        if (goodsId == null) {
            return AjaxResult.error("商品ID不能为空");
        }

        Goods goods = goodsService.selectGoodsByGoodsId(goodsId);

        // 验证是否属于小程序绑定的商家
        Long merchantId = getMiniAppMerchantId();
        if (merchantId != null && !merchantId.equals(goods.getMerchantId())) {
            return AjaxResult.error("商品不存在");
        }

        // 处理分销关系自动绑定
        AjaxResult bindResult = handleDistributionRelation(goodsId, distributorCode, inviteCode);

        if (bindResult != null) {
            // 构建返回结果，包含商品信息和绑定结果
            Map<String, Object> result = new HashMap<>();
            result.put("goods", goods);
            result.put("bindResult", bindResult);
            return success(result);
        }

        return success(goods);
    }

    /**
     * 处理分销关系自动绑定
     * @param goodsId 商品ID
     * @param distributorCode 分销员编码
     * @param inviteCode 邀请码
     * @return 绑定结果，成功返回null，失败返回错误信息
     */
    private AjaxResult handleDistributionRelation(Long goodsId, String distributorCode, String inviteCode) {
        try {
            // 如果传入了分销员编码或邀请码，则进行自动绑定
            if (StringUtils.isNotEmpty(distributorCode) || StringUtils.isNotEmpty(inviteCode)) {
                // 获取当前登录用户
                LoginUser loginUser = getLoginUser();
                if (loginUser == null) {
                    return AjaxResult.error("用户未登录");
                }

                Long userId = loginUser.getUserId();

                // 优先使用分销员编码，如果分销员编码为空则使用邀请码
                String bindCode = StringUtils.isNotEmpty(distributorCode) ? distributorCode : inviteCode;

                // 检查用户是否已经是分销员
                boolean isDistributor = distributionUserService.checkUserHasDistributor(userId);
                if (isDistributor) {
                    logger.info("用户 {} 已经是分销员，无需重复绑定分销关系", userId);
                    Map<String, Object> bindInfo = new HashMap<>();
                    bindInfo.put("bindSuccess", false);
                    bindInfo.put("message", "您已经是分销员，无需重复绑定");
                    return AjaxResult.success("用户已经是分销员", bindInfo);
                }

                // 根据分销员编码获取分销员ID
                DistributionUser distributor = distributionUserService.selectDistributionUserByDistributorCode(bindCode);
                if (distributor == null) {
                    Map<String, Object> bindInfo = new HashMap<>();
                    bindInfo.put("bindSuccess", false);
                    bindInfo.put("message", "分销员不存在");
                    return AjaxResult.error("分销员不存在", bindInfo);
                }

                // 调用分销服务进行自动绑定
                int result = distributionUserService.autoBindRelation(bindCode, userId);

                // 构建绑定结果信息
                Map<String, Object> bindInfo = new HashMap<>();
                if (result > 0) {
                    logger.info("用户 {} 通过商品 {} 的分销二维码成功绑定分销关系，分销员ID: {}, 绑定码: {}",
                        userId, goodsId, distributor.getDistributorId(), bindCode);

                    // 将分销关系存入缓存，供下单时使用（有效期为60分钟）
                    distributionRelationCacheService.cacheTemporaryRelation(userId, distributor.getDistributorId(), goodsId, 60);

                    bindInfo.put("bindSuccess", true);
                    bindInfo.put("message", "分销关系绑定成功");
                    bindInfo.put("distributorCode", bindCode);
                    bindInfo.put("distributorId", distributor.getDistributorId());
                    bindInfo.put("bindTime", new Date());
                    return AjaxResult.success("分销关系绑定成功", bindInfo);
                } else {
                    logger.warn("用户 {} 通过商品 {} 的分销二维码绑定分销关系失败，绑定码: {}", userId, goodsId, bindCode);
                    bindInfo.put("bindSuccess", false);
                    bindInfo.put("message", "分销关系绑定失败");
                    return AjaxResult.error("分销关系绑定失败", bindInfo);
                }
            }
        } catch (Exception e) {
            logger.error("自动绑定分销关系异常", e);
            return AjaxResult.error("分销关系绑定失败：" + e.getMessage());
        }

        return null; // 没有绑定操作，返回null
    }

    /**
     * 新增商品信息
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:goods:add')")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Goods goods)
    {
        return toAjax(goodsService.insertGoods(goods));
    }

    /**
     * 修改商品信息
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:goods:edit')")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Goods goods)
    {
        return toAjax(goodsService.updateGoods(goods));
    }

    /**
     * 删除商品信息
     */
//    @PreAuthorize("@ss.hasPermi('ruoyi:goods:remove')")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{goodsIds}")
    public AjaxResult remove(@PathVariable Long[] goodsIds)
    {
        return toAjax(goodsService.deleteGoodsByGoodsIds(goodsIds));
    }

    /**
     * 根据商品id 剔除已经录入在库存日志中的商品信息
     * 查询商品信息列表
     */
    // @PreAuthorize("@ss.hasPermi('ruoyi:goods:list')")
    @GetMapping("/excludeExistsGoods")
    public TableDataInfo excludeExistsGoods(Goods goods)
    {
        startPage();
        List<Goods> list = goodsService.excludeExistsGoods(goods);
        return getDataTable(list);
    }

    /**
     * 获取小程序端的商家ID
     * @return 商家ID
     */
    private Long getMiniAppMerchantId() {
        // 从配置文件中读取小程序商家ID
        return miniAppMerchantId;
    }
}
